package com.cellulam.framework.fs.excel.utils;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import static org.apache.poi.ss.usermodel.CellType.NUMERIC;

/**
 *
 */
public abstract class CellUtils {

    /**
     * 获取文本值
     *
     * @param cell
     * @return
     */
    public static String toText(Cell cell) {
        return getFieldStrValue(cell);
    }


    /**
     * 获取文本值
     *
     * @param cell
     * @return
     */
    public static String getFieldStrValue(Cell cell) {
        if (cell == null) {
            return null;
        }

        CellType cellType = cell.getCellTypeEnum();
        switch (cellType) {
            case BLANK:
                return null;
            case STRING:
                return cell.toString().trim();
        }

        if (cellType == NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                if (cell.getDateCellValue() == null) {
                    return null;
                }
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
            } else {
                DecimalFormat df = new DecimalFormat("#########.######");
                return String.valueOf(df.format(cell.getNumericCellValue()));
            }
        }

        return cell.toString();
    }

}
